//
//  LCNewsHTMLDetailsVC.m
//  JK九酷云头条
//
//  Created by jiukuyinyue on 2017/11/3.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCNewsHTMLDetailsVC.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "LCNewsHTMLDetailsVC+Create.h"
#import <PAWebView.h>
//#import "UIViewController+LCMBProgressHUD.h"

@interface LCNewsHTMLDetailsVC () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIProgressView *loadingProgressView;

@property (nonatomic, strong) UIButton *reloadButton;

@end

@implementation LCNewsHTMLDetailsVC


- (void)dealloc {
//    [[PAWebView shareInstance] removeObserver:self forKeyPath:@"isloadSuccess" context:nil];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView stopLoading];
    _webView.scrollView.delegate = nil;
    _webView.UIDelegate = nil;
    _webView.navigationDelegate = nil;
    [self.loadingProgressView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    ///设置刷新
    [self setupRefresh];

    self.view.backgroundColor = [UIColor whiteColor];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_url]];//创建URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    [self setupTitleImageView];
    //设置双击
    [self setupDoubleTapOne];
//    [PAWebView shareInstance].view.hidden = NO;
//    NSString *response = [PAWebView shareInstance].webView.title;
//    NSLog(@"response = %@", response);
//        if ([response containsString:@"Error"] || [response isEqualToString:@""]) {
//            [[PAWebView shareInstance] reloadFromOrigin];
//        }
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if ([PAWebView shareInstance].isloadSuccess == YES) {
//                [[PAWebView shareInstance].wkProgressView setAlpha:0.0f];
//        }
//    });
//
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFailFromNotification:) name:@"LCPAWebViewLoadFail" object:nil];
//    [[PAWebView shareInstance] addObserver:self forKeyPath:@"isloadSuccess" options:NSKeyValueObservingOptionNew context:nil];
}
///设置刷新
-(void)setupRefresh{
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_scrollView];
}
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//    if ([keyPath isEqualToString:@"isloadSuccess"]) {
//        NSLog(@"isloadSuccess is changed! new = %@",[change valueForKey:NSKeyValueChangeNewKey]);
//        if ([[change valueForKey:NSKeyValueChangeNewKey] boolValue]== YES) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [PAWebView shareInstance].webView.hidden = NO;
//            });
//        }
//    }
//}

/////访问失败通知执行方法
//-(void)loadFailFromNotification:(NSNotification *)noti{
//    [self example1];
//}
//#pragma mark - Alert loadFail 加载失败弹出框
//- (void)example1 {
//    [PAWebView shareInstance].link = nil;
//    [[PAWebView shareInstance] showErrorMessage:@"网页加载失败，请稍后重试!"];
//}


-(void)back{
//    if ([PAWebView shareInstance].isloadSuccess == YES) {
//        [[PAWebView shareInstance].wkProgressView setAlpha:0.0f];
//    }
    [self closePAWebView];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LCPAWebViewLoadFail" object:nil];
//    [[PAWebView shareInstance] hideAllHudWithDelay:0];
//    [self.navigationController popViewControllerAnimated:YES];
//    if ([PAWebView shareInstance].view.hidden == NO) {
//        NSLog(@"no hidden = ");
//    }
}
- (void)closePAWebView{
    self.loadingProgressView.hidden = YES;
//    [PAWebView shareInstance].view.hidden = YES;
////    NSArray<WKBackForwardListItem *> *history = [[PAWebView shareInstance].webView.backForwardList backList];//历史记录的列表
////    if (history.count > 0) {
////        [[PAWebView shareInstance].webView goToBackForwardListItem:history[0]];//跳转想对应网页的操作
////    }
////    id internalWebView=[[PAWebView shareInstance] webView];
////    [internalWebView setMaintainsBackForwardList:NO];
////    [internalWebView setMaintainsBackForwardList:YES];
//    [[PAWebView shareInstance].view removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}


///设置双击
- (void)setupDoubleTapOne {
    UITapGestureRecognizer *doubleTapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    //表示几个手指点击时 触发事件，默认值为1
    doubleTapOne.numberOfTouchesRequired = 1;
    //几次点击时触发事件 ,默认值为1
    doubleTapOne.numberOfTapsRequired = 1;
    doubleTapOne.delegate = self;
    if([LSZSpecialPackaging isDoubleClickSwitch]) {
        [_webView addGestureRecognizer:doubleTapOne];
    }
}
///双击点击方法 利用时间计算间隔判断是否双击事件
- (void)handleDoubleTap:(UITapGestureRecognizer *)swipe{
    
    NSDate *date = [[NSDate alloc] init];
//    JKLog(@"date = %zd", date.timeIntervalSince1970);
    if (date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 < 0.4) {
//        JKLog(@"date = %zd", date.timeIntervalSince1970);
        if([LSZSpecialPackaging isDoubleClickSwitch]) {
            if (!self.isDragging) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            }
        }
    }
    _lastDate = date;
}
/// 允许多个手势并发
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

/// 设置导航栏
- (UIView *)setupViewTop {
    UIView * viewTop = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, NAVIGATION_BAR_HEIGHT)];
    viewTop.backgroundColor = RGBColor(224,106,103);
    viewTop.userInteractionEnabled = YES;
    [self.view addSubview:viewTop];
    return viewTop;
}
///设置左button返回
- (void)leftButton:(UIView *)viewTop {
    UIButton * but = [[UIButton alloc]init];
    but.frame = CGRectMake(0, 0, 100, NAVIGATION_BAR_HEIGHT);
    [but addTarget:self action:@selector(clickButReturn) forControlEvents:UIControlEventTouchUpInside];
    [viewTop addSubview:but];
    UIImageView * imageViewReturn = [[UIImageView alloc]initWithFrame:CGRectMake(20, but.frame.size.height-35, 11, 20)];
    imageViewReturn.image = [UIImage imageNamed:@"home_nav_button_back"];
    [viewTop addSubview:imageViewReturn];
}
-(void)clickButReturn {
    [self dismissViewControllerAnimated:YES completion:NULL];
}
///设置进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.loadingProgressView setProgress:[change[@"new"] floatValue] animated:YES];
        if (_loadingProgressView.progress == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                _loadingProgressView.hidden = YES;
            });
        }
    }
    if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }
}

/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *strURL = (navigationAction.request.URL.absoluteString);
    NSLog(@"strURL = %@", strURL);
    if (_loadingProgressView.progress == 1.0) {//用来判断已经加载过网页
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _loadingProgressView.hidden = NO;
        });
    }
    // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (WKWebView*)webView {
    if (!_webView) {
        _webView = [self createWebView:self.scrollView];
        //布局
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self.view);
        }];
    }
    return _webView;
}
///加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *response = webView.title;
    NSLog(@"response = %@", response);
    if ([response containsString:@"Error"] || [response isEqualToString:@""]) {
        [webView reloadFromOrigin];
    }

////    hideArt();";
//    //document.getElementsByClassName('more').onclick=function(){ window.webkit.messageHandlers.back.postMessage(null) };";//document.body.ondblclick=function(){ alert ('ondblclick'); }; ";
//    //document.getElementsByClassName('g-wrapper').onclick=function(){ window.webkit.messageHandlers.back.postMessage(null) };
//    //document.write('<h1>Hello World!</h1>');
//    ///加载更多
//    NSString *doc = @" $('.g-wrapper').css('height', 'auto');";
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//        [_webView evaluateJavaScript:doc
//                   completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
//                       if (error) { NSLog(@"JSError:%@",error); }
////                       NSLog(@"ondblclick:%@",htmlStr);
//                       //立即执行隐藏加载更多
//                       NSString *doc1 = @"$('.more').hide();";//@"document.body.outerHTML";
//                       [_webView evaluateJavaScript:doc1
//                                  completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
//                                      if (error) { NSLog(@"JSError:%@",error); }
//                      //                   NSLog(@"html:%@",htmlStr);
//                                  }] ;
//
////                       //立即执行获取高度
////                       NSString *doc2 = @"window.document.body.clientHeight";
////                       [_webView evaluateJavaScript:doc2
////                                  completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
////                                      if (error) { NSLog(@"JSError:%@",error); }
//////                                     NSLog(@"html:%@",htmlStr);
//////                                      _webView.frame = CGRectMake(0, 0, ScreenWidth, [htmlStr floatValue]);
////                                  }] ;
//                   }] ;
//    });
//
////    [_webView.configuration.userContentController addScriptMessageHandler:self name:@"back"];
}
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
//    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
}

- (UIProgressView*)loadingProgressView {
    if (!_loadingProgressView) {
        //设置网页加载进度条
        _loadingProgressView = [self createLoadingProgressView:self.navigationController.navigationBar];
    }
    return _loadingProgressView;
}

///页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    [super example1];
}
- (UIButton*)reloadButton {
    if (!_reloadButton) {
        //刷新按钮
        _reloadButton = [self createReloadButton:self.view];
        [_reloadButton addTarget:self action:@selector(reloadButtonClick) forControlEvents:UIControlEventTouchUpInside];
     }
    return _reloadButton;
}

///重置网页加载进度指示器
- (void)resetLoading {
    _loadingProgressView.progress = 0;
    _loadingProgressView.hidden = NO;
}

///刷新网页, 重新加载网页
- (void)refreshWebView {
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_url]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
    _webView.hidden = NO;
}

-(void)reloadButtonClick {
    [self resetLoading];//重置网页加载进度指示器

    [self refreshWebView];//刷新网页, 重新加载网页
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _isDragging = YES;
//    JKLog(@"scrollView.contentOffset.y = %f", scrollView.contentOffset.y);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        NSLog(@"scrollViewDidEndDragging ");
        _isDragging = NO;
    });
}

@end
